package com.ibm.ibank.shareddatasource;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.zaxxer.hikari.HikariDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * 可共享连接的数据源。对只读事务，共用一条连接，以节省连接数。
 * 
 * @author WeiZhou
 *
 */
@Slf4j
public class SharedDataSource extends HikariDataSource {
	SharedConnectionWrapper sharedConn = null;
	@Override
	public Connection getConnection() throws SQLException {
		boolean readonly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
		if (readonly) {
			if (isClosed()) {
				throw new SQLException("SharedDatasource " + this + " has been closed.");
			}
			if (sharedConn == null || sharedConn.isClosed()) {
				synchronized (this) {
					if (sharedConn == null || sharedConn.isClosed()) {
						sharedConn = new SharedConnectionWrapper(super.getConnection());
//						sharedConn.setAutoCommit(true);
//						sharedConn.setReadOnly(true);
					}
				}
			} else {
				// TODO valid the connection in some time;max-idle-time
				// spring.datasource.time-between-eviction-runs-millis=18800
			}
			if (log.isTraceEnabled())
				log.trace("readonly:" + sharedConn.isReadOnly() + " closed:" + sharedConn.isClosed()
						+ " lvl:" + sharedConn.getTransactionIsolation() + " auto:" + sharedConn.getAutoCommit());
			return sharedConn;
		}
		return super.getConnection();
	}

}
